﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using Microsoft.EntityFrameworkCore;

using Digitalmes.ViewModel._Admin.FrameworkUserVMs;
using Digitalmes.ViewModel.ProductManagement.ProductVMs;
using Digitalmes.Model.FactoryManagement;
using Digitalmes.Model;
using System.Text.Json.Serialization;
using Digitalmes.Model.EquipmentManagement;
using Digitalmes.Model.ProductManagement;
namespace Digitalmes.ViewModel.FactoryManagement.ProductionLineVMs
{
    public partial class ProductionLineVM : BaseCRUDVM<ProductionLine>
    {
        /// <summary>
        /// 当前已选择关联设备
        /// </summary>
        [Display(Name = "_Model.Equipment")]
        public List<string> SelectedEquipmentProductionLines { get; set; }

        /// <summary>
        /// 历史选择关联设备
        /// </summary>
        public List<string> OldSelectedEquipmentProductionLines { get; set; }


        /// <summary>
        /// 当前选择的生产产品
        /// </summary>
        [Display(Name = "_Model.Product")]
        public List<string> SelectedProductProductionLines { get; set; }

        /// <summary>
        /// 历史选择生产产品
        /// </summary>
        public List<string> OldSelectedProductProductionLines { get; set; }

        public ProductionLineVM()
        {
            
            SetInclude(x => x.PrincipalId);
            //SetInclude(x => x.Product);
            SetInclude(x => x.LineShift_Line);
            SetInclude(x => x.EquipmentProductionLines);
            SetInclude(x => x.ProductProductionLines);

        }

        protected override void InitVM()
        {

            SelectedEquipmentProductionLines = Entity.EquipmentProductionLines?.Select(x => x.EquipmentId.ToString()).ToList();
          

            SelectedProductProductionLines = Entity.ProductProductionLines?.Select(x => x.ProductId.ToString()).ToList();

            //保存原来选择的关联设备
            OldSelectedEquipmentProductionLines = Entity.EquipmentProductionLines?.Select(x => x.EquipmentId.ToString()).ToList();
            //保存原来选择的产品
            OldSelectedProductProductionLines = Entity.ProductProductionLines?.Select(x => x.ProductId.ToString()).ToList();

        }

        public override DuplicatedInfo<ProductionLine> SetDuplicatedCheck()
        {
            return null;

        }

        /// <summary>
        /// 事务处理机制
        /// </summary>
        /// <returns></returns>
        public override async Task DoAddAsync()
        {
           
            if (SelectedEquipmentProductionLines != null)
            {
                Entity.EquipmentProductionLines = new List<EquipmentProductionLine>();
                foreach (var id in SelectedEquipmentProductionLines)
                {
                    EquipmentProductionLine middle = new EquipmentProductionLine();
                    middle.SetPropertyValue("EquipmentId", id);
                    middle.SetPropertyValue("TenantCode", LoginUserInfo.CurrentTenant);
                    Entity.EquipmentProductionLines.Add(middle);
                    var equipment=DC.Set<Equipment>().CheckID(id).FirstOrDefault();    
                    if (equipment != null)
                    {
                        equipment.Line = Entity;
                        DC.Set<Equipment>().Update(equipment);                       
                    }
                }
            }
           


            if (SelectedProductProductionLines != null)
            {
                Entity.ProductProductionLines = new List<ProductProductionLine>();
                foreach (var id in SelectedProductProductionLines)
                {
                    ProductProductionLine middle = new ProductProductionLine();
                    middle.SetPropertyValue("ProductId", id);
                    middle.SetPropertyValue("TenantCode", LoginUserInfo.CurrentTenant);
                    Entity.ProductProductionLines.Add(middle);
                    var prod=DC.Set<Product>().CheckID(id).FirstOrDefault();    
                    if (prod != null)
                    {
                        prod.Line = Entity;
                        DC.Set<Product>().Update(prod); 
                    }
                }
            }
           

            await base.DoAddAsync();

        }

        /// <summary>
        /// 事务处理机制
        /// </summary>
        /// <param name="updateAllFields"></param>
        /// <returns></returns>
        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            
            if (SelectedEquipmentProductionLines != null)
            {
                Entity.EquipmentProductionLines = new List<EquipmentProductionLine>();
                foreach (var id in SelectedEquipmentProductionLines)
                {
                    EquipmentProductionLine middle = new EquipmentProductionLine();
                    middle.SetPropertyValue("EquipmentId", id);
                    middle.SetPropertyValue("TenantCode", LoginUserInfo.CurrentTenant);
                    Entity.EquipmentProductionLines.Add(middle);
                }
              
            }
            await HandleEquipmentAssociations();

            if (SelectedProductProductionLines != null)
            {
                Entity.ProductProductionLines = new List<ProductProductionLine>();
                foreach (var id in SelectedProductProductionLines)
                {
                    ProductProductionLine middle = new ProductProductionLine();
                    middle.SetPropertyValue("ProductId", id);
                    middle.SetPropertyValue("TenantCode", LoginUserInfo.CurrentTenant);
                    Entity.ProductProductionLines.Add(middle);
                }
            }

            await HandleProductAssociations();

            await base.DoEditAsync();

        }



        /// <summary>
        /// 处理设备关联关系（新增/移除）
        /// </summary>
        private async Task HandleEquipmentAssociations()
        {
            // 确保集合不为null
            var currentEquipmentIds = SelectedEquipmentProductionLines ?? new List<string>();
            var oldEquipmentIds = OldSelectedEquipmentProductionLines ?? new List<string>();

            // 计算新增和移除的设备ID
            var addedEquipmentIds = currentEquipmentIds.Except(oldEquipmentIds).ToList();
            var removedEquipmentIds = oldEquipmentIds.Except(currentEquipmentIds).ToList();

            // 处理新增的设备关联
            foreach (var equipmentId in addedEquipmentIds)
            {
                var equipment = await DC.Set<Equipment>()
                    .CheckID(equipmentId)
                    .FirstOrDefaultAsync();
                if (equipment != null)
                {
                    equipment.LineId = Entity.ID;
                    equipment.Line = Entity;
                   
                    DC.Set<Equipment>().Update(equipment);
                }
            }

            // 处理移除的设备关联
            foreach (var equipmentId in removedEquipmentIds)
            {
                var equipment = await DC.Set<Equipment>()
                    .CheckID(equipmentId)
                    .FirstOrDefaultAsync();
                if (equipment != null)
                {
                    equipment.Line = null;
                    equipment.LineId = null;
                    DC.Set<Equipment>().Update(equipment);
                }
            }
        }

        /// <summary>
        /// 处理产品关联关系（新增/移除）
        /// </summary>
        private async Task HandleProductAssociations()
        {
            // 确保集合不为null
            var currentProductIds = SelectedProductProductionLines ?? new List<string>();
            var oldProductIds = OldSelectedProductProductionLines ?? new List<string>();

            // 计算新增和移除的产品ID
            var addedProductIds = currentProductIds.Except(oldProductIds).ToList();
            var removedProductIds = oldProductIds.Except(currentProductIds).ToList();

            // 处理新增的产品关联
            foreach (var productId in addedProductIds)
            {
                var product = await DC.Set<Product>()
                    .CheckID(productId)
                    .FirstOrDefaultAsync();
                if (product != null)
                {
                    product.LineId = Entity.ID;
                    product.Line = Entity;                   
                    DC.Set<Product>().Update(product);
                }
            }

            // 处理移除的产品关联
            foreach (var productId in removedProductIds)
            {
                var product = await DC.Set<Product>()
                    .CheckID(productId)
                    .FirstOrDefaultAsync();
                if (product != null)
                {
                    product.Line = null;
                    product.LineId = null;
                    DC.Set<Product>().Update(product);
                }
            }
        }

        public override async Task DoDeleteAsync()
        {
            await base.DoDeleteAsync();
        }
    }
}
